#include "PercentPositionerWidget.h"

#include "Math/Math.h"
#include "Output/Console.h"

void RPercentPositionerWidget::CalculatePresentPositionAndSize()
{
    bChildrenArranged=false;
    Super::CalculatePresentPositionAndSize();
}

void RPercentPositionerWidget::CalculateChildrenPresentPositionAndSize()
{
    if(!bChildrenArranged)
    {
        ArrangeChildren();
    }
    
    Super::CalculateChildrenPresentPositionAndSize();

}

float RPercentPositionerWidget::CalculateContentWidth()
{
    if(!bChildrenArranged)
    {
        ArrangeChildren();
    }
    return ContentSize.X;
}

float RPercentPositionerWidget::CalculateContentHeight()
{
    if(!bChildrenArranged)
    {
        ArrangeChildren();
    }
    return ContentSize.Y;
}

void RPercentPositionerWidget::ArrangeChildren()
{
    assert(bChildrenArranged==false);
    bChildrenArranged=true;

    if(SubWidgets.Empty())
    {
        return;
    }

    if(SubWidgets.Num()>1)
    {
        WH::PrintLine(U"RPercentPositionerWidget only worked on first child,other children will be ignored.");
    }

    auto Child=SubWidgets[0];
    Child->CalculateSelfPresentPositionAndSize();

    float _Width=Child->PresentSize.X;
    {
        float _XPercent=XPercent.Get();
        _XPercent=CMath::Clamp(_XPercent,0.f,1.f);
     
        float _ParentWidth=PresentSize.X;
        float _X=- _Width*_XPercent;
        _X=CMath::Clamp(_X,-_Width,0);
        Child->X = _X;
    }


    float _Height=Child->PresentSize.Y;
    {
        float _YPercent=YPercent.Get();
        _YPercent=CMath::Clamp(_YPercent,0.f,1.f);
     
        float _ParentHeight=PresentSize.Y;
        float _Y=- _Height*_YPercent;
        _Y=CMath::Clamp(_Y,-_Height,0);
        Child->Y = _Y;
    }

}